package producer

import (
	"context"
	"fmt"
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
	"time"
)

// SendMessage 向 RocketMQ 发送消息
func SendMessage(nameServerAddr, topic, messageBody string, groupName string) error {
	// 创建一个新的生产者实例
	p, err := rocketmq.NewProducer(
		producer.WithGroupName(groupName),
		producer.WithNsResolver(primitive.NewPassthroughResolver([]string{nameServerAddr})),
	)
	if err != nil {
		return fmt.Errorf("failed to create producer: %w", err)
	}

	// 启动生产者
	err = p.Start()
	if err != nil {
		return fmt.Errorf("failed to start producer: %w", err)
	}
	defer func(p rocketmq.Producer) {
		_ = p.Shutdown()
	}(p)

	// 创建消息
	msg := &primitive.Message{
		Topic: topic,
		Body:  []byte(messageBody),
	}

	// 发送消息
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	result, err := p.SendSync(ctx, msg)
	cancel()
	if err != nil {
		return fmt.Errorf("failed to send message: %w", err)
	}

	fmt.Printf("Message sent successfully, message ID: %s\n", result.MsgID)
	return nil
}
